import type { NavigationGuardNext, RouteLocationNormalized, RouteRecordRaw } from "vue-router";
import NProgress from "@/utils/nprogress";
import { Auth } from "@/utils/auth";
import router from "@/router";
import { usePermissionStore, usePermissionStoreHook, useUserStore } from "@/store";
import { ROLE_ROOT } from "@/constants";
import { Store } from "pinia";

export function setupPermission() {
  /**
   * 前置守卫逻辑：
   * router.beforeEach
   * 1、判断是否去登录页或公开页面；
   *   1、如果去登录页或公开页面，放行；
   * 2、判断用户是否已登录；
   *   1、如果未登录，重定向到登录页；
   * 3、判断是否加载路由；
   *   1、如果已加载路由，判断路由是否匹配；
   *     1、如果路由未匹配，跳转到404；
   *     2、如果路由匹配，设置页面标题；
   *   2、如果未加载路由，则调用 生成动态路由 方法
   * 4、放行；
   */
  router.beforeEach(async (to, from, next) => {
    NProgress.start();
    console.log("to.path", to.path);
    
    // 公开页面，不需要登录即可访问
    const publicPaths = ["/login", "/501", "/404", "/401"];
    
    // 如果访问的是公开页面，直接放行
    if (publicPaths.includes(to.path)) {
      next();
      return;
    }
    
    // 检查用户是否已登录
    const isLoggedIn = Auth.isLoggedIn();
    
    // 如果未登录且访问的不是公开页面，重定向到登录页
    if (!isLoggedIn) {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`);
      NProgress.done();
      return;
    }
    
    // 用户已登录，继续处理路由
    const permissionStore = usePermissionStore();
    console.log("permissionStore.routesLoaded", permissionStore.routesLoaded);
    if (permissionStore.routesLoaded) {
      if (to.matched.length === 0) {
        next("/404");
      } else {
        next();
      }
    } else {
      try {
        const dynamicRoutes = await permissionStore.generateRoutes();
        dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route));
        next({ ...to, replace: true });
      } catch (error) {
        console.error(error);
        // 路由加载失败，重置 token 并重定向到 501 页面，传递错误信息
        Auth.clearAuth();
        await useUserStore().resetAllState();
        next({
          path: "/501",
          query: { msg: encodeURIComponent(error?.toString?.() || "路由加载失败") },
        });
        NProgress.done();
      }
    }
  });

  // 后置守卫，保证每次路由跳转结束时关闭进度条
  router.afterEach(() => {
    NProgress.done();
  });
}

async function add_permission_routes(
  permissionStore: ReturnType<typeof usePermissionStoreHook>,
  to: RouteLocationNormalized,
  next: NavigationGuardNext
) {
  if (permissionStore.routesLoaded) {
    if (to.matched.length === 0) {
      // 路由未匹配，跳转到404
      next("/404");
    } else {
      // 动态设置页面标题
      const title = (to.params.title as string) || (to.query.title as string);
      if (title) {
        to.meta.title = title;
      }
      next();
    }
  } else {
    try {
      // 生成动态路由
      const dynamicRoutes = await permissionStore.generateRoutes();
      dynamicRoutes.forEach((route: RouteRecordRaw) => router.addRoute(route));
      next({ ...to, replace: true });
    } catch (error) {
      console.error(error);
      // 路由加载失败，重置 token 并重定向到登录页
      await useUserStore().resetAllState();
      // redirectToLogin(to, next);
      redirectToDashboard(to, next);
      NProgress.done();
    }
  }
}

// 重定向到登录页
function redirectToLogin(to: RouteLocationNormalized, next: NavigationGuardNext) {
  const params = new URLSearchParams(to.query as Record<string, string>);
  const queryString = params.toString();
  const redirect = queryString ? `${to.path}?${queryString}` : to.path;
  next(`/login?redirect=${encodeURIComponent(redirect)}`);
}

// 重定向到主页仪表盘 dashboard
function redirectToDashboard(to: RouteLocationNormalized, next: NavigationGuardNext) {
  next({ path: "/hmi-dashboard" });
}

/** 判断是否有权限 */
export function hasAuth(value: string | string[], type: "button" | "role" = "button") {
  const { roles, perms } = useUserStore().userInfo;

  // 超级管理员 拥有所有权限
  if (type === "button" && roles.includes(ROLE_ROOT)) {
    return true;
  }

  const auths = type === "button" ? perms : roles;
  return typeof value === "string"
    ? auths.includes(value)
    : value.some((perm) => auths.includes(perm));
}
